package com.ztools.pc.provider;

import cn.hutool.core.util.StrUtil;
import com.ztools.api.service.pc.PcStudentService;
import com.ztools.api.service.wx.WxMsgService;
import com.ztools.common.model.pc.information.WeChatMember;
import com.ztools.common.util.common.Result;
import com.ztools.pc.service.information.MemberService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import static com.ztools.common.util.pc.RedisUtil.UPDATE_MEMBER_NICKNAME_LIMIT_PREFIX;

/**
 * @Author:seeTools
 * @Date: 2023/4/8  21:48
 * @Version 1.0
 */
@Service(version = "1.0", timeout = 3000)
public class PcStudentServiceImpl implements PcStudentService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private MemberService memberService;
    @Reference(version = "1.0", check = false, timeout = 6000)
    private WxMsgService wxMsgService;

    @Override
    public Result subscribe(WeChatMember weChatMember) {
        if (StrUtil.isBlank(weChatMember.getOpenid())) {
            return Result.error("参数不完整：openid不能为空");
        }
        WeChatMember member = memberService.findByOpenId(weChatMember.getOpenid());
        if (member != null) {
            weChatMember.setName(member.getName());
            // 已关注状态
            weChatMember.setMemberStatus(0);
            memberService.update(weChatMember);
            return Result.success("粉丝已存在系统，无需再次关注");
        }
        weChatMember.setMemberStatus(1);
        weChatMember.setModifiedDate(new Date());
        memberService.save(weChatMember);
        // 发送客户消息
        return wxMsgService.sendKeFuMessage(weChatMember.getOpenid(), "你来啦，o(*////▽////*)q！ 欢迎关注");
    }

    @Override
    public void updateMemberNickName(String openId, String nickName) {
        String redisKey = UPDATE_MEMBER_NICKNAME_LIMIT_PREFIX + openId;
        Boolean hasKey = stringRedisTemplate.hasKey(redisKey);
        if (hasKey != null && !hasKey) {
            WeChatMember memberInfo = memberService.findByOpenId(openId);
            if (memberInfo != null && !nickName.equals(memberInfo.getNickName())) {
                logger.info("update nickName from {} to {}", memberInfo.getNickName(), nickName);
                memberService.updateNickName(memberInfo.getId(), nickName);
                stringRedisTemplate.opsForValue().set(redisKey, nickName, 1L, TimeUnit.DAYS);
            }
        }
    }

}
